//
//  QuickEditBookViewModel.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 10.05.25.
//

import Foundation
class QuickEditBookViewModel : KoiAccountingBaseViewModel {
    
    @Published var detail: AccountingDetailCombine
    
    @Published var books: [AccountingBook] = [AccountingBook]()
    
    @Published var selectedBook: AccountingBook
    @Published var selectedCategory: AccountingCategory
    
    @Published var expenseList: [AccountingCategory] = [AccountingCategory]()
    @Published var incomeList: [AccountingCategory] = [AccountingCategory]()
    @Published var updateState: String = ""
    
    private let bookDao = KoiAccountingDB.standard.getBookDao()
    private let categoryDao = KoiAccountingDB.standard.getCategoryDao()
    private let detailDao = KoiAccountingDB.standard.getDetailDao()
    
    init(detail: AccountingDetailCombine) {
        self.detail = detail
        self.selectedBook = detail.book
        self.selectedCategory = detail.category
    }
    
    func loadBooks() {
        asyncBackground {
            let books = self.bookDao.getAllBook(uid: self.uid)
            self.asyncMain {
                self.books = books
            }
        }
    }
    
    func updateBook() {
        let bookId = selectedBook.bookId
        let cid = selectedCategory.cid
        var detail = detail.detail
        asyncBackground {
            detail.cid = cid
            detail.bookId = bookId
            self.detailDao.updateRecord(detail: detail)
            self.asyncMain {
                self.updateState = "success"
            }
        }
    }
}
